<?php

/**
 * [PHPFOX_HEADER]
 */
defined('PHPFOX') or exit('NO DICE!');

class SocialLogin_Service_SocialLogin extends Phpfox_Service {

    public function HeaderLogin() {
        Phpfox::getBlock('sociallogin.headerLogin', array());
    }

    private function _getSalt($iTotal = 3) {
        $sSalt = '';
        for ($i = 0; $i < $iTotal; $i++) {
            $sSalt .= chr(rand(33, 91));
        }
        return $sSalt;
    }

    public function addUser($aVals, $iUserGroupId = null) {

        if (!defined('PHPFOX_INSTALLER') && !Phpfox::getParam('user.allow_user_registration')) {

            return Phpfox_Error::display(Phpfox::getPhrase('user.user_registration_has_been_disabled'));
        }

        $oParseInput = Phpfox::getLib('parse.input');
        $sSalt = $this->_getSalt();

        if (!Phpfox_Error::isPassed()) {
            return false;
        }

        if (!defined('PHPFOX_INSTALLER') && Phpfox::getParam('user.validate_full_name')) {
            if (!Phpfox::getLib('validator')->check($aVals['full_name'], array(
                        'html',
                        'url'
                    ))) {
                return Phpfox_Error::set(Phpfox::getPhrase('user.not_a_valid_name'));
            }
        }

        if (!defined('PHPFOX_INSTALLER') && !Phpfox::getService('ban')->check('display_name', $aVals['full_name'])) {
            Phpfox_Error::set(Phpfox::getPhrase('user.this_display_name_is_not_allowed_to_be_used'));
        }
        if (!defined('PHPFOX_INSTALLER')) {
            if (!defined('PHPFOX_SKIP_EMAIL_INSERT')) {
                if (!Phpfox::getLib('mail')->checkEmail($aVals['email'])) {
                    return Phpfox_Error::set(Phpfox::getPhrase('user.email_is_not_valid'));
                }
            }

            if (Phpfox::getLib('parse.format')->isEmpty($aVals['full_name'])) {
                Phpfox_Error::set(Phpfox::getPhrase('user.provide_a_name_that_is_not_representing_an_empty_name'));
            }
        }
        $aVals['gender'] = isset($aVals['gender']) ? $aVals['gender'] : 0;
        $aInsert = array(
            'user_group_id' => ($iUserGroupId === null ? NORMAL_USER_ID : $iUserGroupId),
            'full_name' => $oParseInput->clean($aVals['full_name'], 255),
            'password' => Phpfox::getLib('hash')->setHash($aVals['password'], $sSalt),
            'password_salt' => $sSalt,
            'email' => $aVals['email'],
            'joined' => PHPFOX_TIME,
            'gender' => (defined('PHPFOX_INSTALLER') || (!defined('PHPFOX_INSTALLER') && Phpfox::getParam('core.registration_enable_gender')) ? $aVals['gender'] : 0),
            'birthday' => null,
            //'birthday_search' => (defined('PHPFOX_INSTALLER') || (!defined('PHPFOX_INSTALLER') && Phpfox::getParam('core.registration_enable_dob')) ? Phpfox::getLib('date')->mktime(0, 0, 0, $aVals['month'], $aVals['day'], $aVals['year']) : 0),
            'country_iso' => (defined('PHPFOX_INSTALLER') || (!defined('PHPFOX_INSTALLER') && Phpfox::getParam('core.registration_enable_location')) ? $aVals['country_iso'] : null),
            'language_id' => ((!defined('PHPFOX_INSTALLER') && Phpfox::getLib('session')->get('language_id')) ? Phpfox::getLib('session')->get('language_id') : null),
            'time_zone' => (isset($aVals['time_zone']) && (defined('PHPFOX_INSTALLER') || (!defined('PHPFOX_INSTALLER') && Phpfox::getParam('core.registration_enable_timezone'))) ? $aVals['time_zone'] : null),
            'last_ip_address' => Phpfox::getIp(),
            'last_activity' => PHPFOX_TIME
        );

        if (!defined('PHPFOX_INSTALLER') && Phpfox::getParam('user.verify_email_at_signup')) {
            $aInsert['status_id'] = 1;
            // 1 = need to verify email
        }

        if (!defined('PHPFOX_INSTALLER') && Phpfox::getParam('user.approve_users')) {
            $aInsert['view_id'] = '1';
            // 1 = need to approve the user
        }
        $aVals['user_name'] = str_replace(' ', '_', $aVals['user_name']);
        $aInsert['user_name'] = $oParseInput->clean($aVals['user_name']);
        (($sPlugin = Phpfox_Plugin::get('user.service_process_add_start')) ? eval($sPlugin) : false);

        if (!Phpfox_Error::isPassed()) {
            return false;
        }


        $iId = $this->database()->insert(Phpfox::getT('user'), $aInsert);
        $aInsert['user_id'] = $iId;
        $aExtras = array('user_id' => $iId);

        (($sPlugin = Phpfox_Plugin::get('user.service_process_add_extra')) ? eval($sPlugin) : false);

        $array = array(
            'user_activity',
            'user_field',
            'user_space',
            'user_count'
        );

        // please clean elder data because some time user_activity has dirty data. etc: user_activity ac =  5600, but user_id ac =  1345, and it throws error!.
        foreach ($array as $table) {
            $table = Phpfox::getT($table);
            $this->database()->delete($table, 'user_id=' . intval($iId));
            $this->database()->insert($table, $aExtras);
        }

        /* if (Phpfox::getParam('user.profile_use_id') || Phpfox::getParam('user.disable_username_on_sign_up'))
          {
          $this->database()->update(Phpfox::getT('user'), array('user_name' => 'profile-' . $iId), 'user_id = ' . $iId);
          } */

        (($sPlugin = Phpfox_Plugin::get('user.service_process_add_feed')) ? eval($sPlugin) : false);
        if (isset($aVals['country_child_id'])) {
            Phpfox::getService('user.field.process')->update($iId, 'country_child_id', $aVals['country_child_id']);
        }
        if (!defined('PHPFOX_INSTALLER')) {
            $iFriendId = (int) Phpfox::getParam('user.on_signup_new_friend');
            if ($iFriendId > 0) {
                $this->database()->insert(Phpfox::getT('friend'), array(
                    'list_id' => 0,
                    'user_id' => $iId,
                    'friend_user_id' => $iFriendId,
                    'time_stamp' => PHPFOX_TIME
                ));

                $this->database()->insert(Phpfox::getT('friend'), array(
                    'list_id' => 0,
                    'user_id' => $iFriendId,
                    'friend_user_id' => $iId,
                    'time_stamp' => PHPFOX_TIME
                ));

                Phpfox::getService('friend.process')->updateFriendCount($iId, $iFriendId);
                Phpfox::getService('friend.process')->updateFriendCount($iFriendId, $iId);
            }
            if ($sPlugin = Phpfox_Plugin::get('user.service_process_add_check_1')) {
                eval($sPlugin);
            }
            if (!defined('PHPFOX_INSTALLER') && Phpfox::getParam('user.verify_email_at_signup') == false && !isset($bDoNotSendWelcomeEmail)) {
                if (isset($aVals['autopassword'])) {
                    Phpfox::getLib('mail')->to($iId)->subject(array(
                        'core.welcome_email_subject',
                        array('site' => Phpfox::getParam('core.site_title'))
                    ))->message(array(
                        'opensocialconnect.welcome_email_content_sign_up',
                        array(
                            'email' => $aVals['email'],
                            'password' => $aVals['password']
                        )
                    ))->send();
                } else {
                    Phpfox::getLib('mail')->to($iId)->subject(array(
                        'core.welcome_email_subject',
                        array('site' => Phpfox::getParam('core.site_title'))
                    ))->message(array('core.welcome_email_content'))->send();
                }
            }

            switch (Phpfox::getParam('user.on_register_privacy_setting')) {
                case 'network' :
                    $iPrivacySetting = '1';
                    break;
                case 'friends_only' :
                    $iPrivacySetting = '2';
                    break;
                case 'no_one' :
                    $iPrivacySetting = '4';
                    break;
                default :
                    break;
            }

            if (isset($iPrivacySetting)) {
                $this->database()->insert(Phpfox::getT('user_privacy'), array(
                    'user_id' => $iId,
                    'user_privacy' => 'profile.view_profile',
                    'user_value' => $iPrivacySetting
                ));
            }
        }

        (($sPlugin = Phpfox_Plugin::get('user.service_process_add_end')) ? eval($sPlugin) : false);

        if (!empty($aCustom)) {
            if (!Phpfox::getService('custom.process')->updateFields($iId, $iId, $aCustom, true)) {
                return false;
            }
        }

        $this->database()->insert(Phpfox::getT('user_ip'), array(
            'user_id' => $iId,
            'type_id' => 'register',
            'ip_address' => Phpfox::getIp(),
            'time_stamp' => PHPFOX_TIME
        ));

        if (!defined('PHPFOX_INSTALLER') && Phpfox::getParam('user.verify_email_at_signup') && !isset($bSkipVerifyEmail)) {
            $aVals['user_id'] = $iId;
            $sHash = Phpfox::getService('user.verify')->getVerifyHash($aVals);
            $this->database()->insert(Phpfox::getT('user_verify'), array(
                'user_id' => $iId,
                'hash_code' => $sHash,
                'time_stamp' => Phpfox::getTime(),
                'email' => $aVals['email']
            ));
            $sLink = Phpfox::getLib('url')->makeUrl('user.verify', array('link' => $sHash));
            // send email
            if (isset($aVals['autopassword'])) {
                Phpfox::getLib('mail')->to($iId)->subject(array(
                    'user.please_verify_your_email_for_site_title',
                    array('site_title' => Phpfox::getParam('core.site_title'))
                ))->message(array(
                    'opensocialconnect.you_registered_an_account_on_site_title_before_being_able_to_use_your_account_you_need_to_verify_tha',
                    array(
                        'site_title' => Phpfox::getParam('core.site_title'),
                        'link' => $sLink,
                        'email' => $aVals['email'],
                        'password' => $aVals['password'],
                    )
                ))->send();
            } else {
                Phpfox::getLib('mail')->to($iId)->subject(array(
                    'user.please_verify_your_email_for_site_title',
                    array('site_title' => Phpfox::getParam('core.site_title'))
                ))->message(array(
                    'user.you_registered_an_account_on_site_title_before_being_able_to_use_your_account_you_need_to_verify_that_this_is_your_email_address_by_clicking_here_a_href_link_link_a',
                    array(
                        'site_title' => Phpfox::getParam('core.site_title'),
                        'link' => $sLink
                    )
                ))->send();
            }
        }

        if (!defined('PHPFOX_INSTALLER') && Phpfox::isModule('subscribe') && Phpfox::getParam('subscribe.enable_subscription_packages') && !empty($aVals['package_id'])) {
            $aPackage = Phpfox::getService('subscribe')->getPackage($aVals['package_id']);
            if (isset($aPackage['package_id'])) {
                $iPurchaseId = Phpfox::getService('subscribe.purchase.process')->add(array(
                    'package_id' => $aPackage['package_id'],
                    'currency_id' => $aPackage['default_currency_id'],
                    'price' => $aPackage['default_cost']
                        ), $iId);

                $iDefaultCost = (int) str_replace('.', '', $aPackage['default_cost']);

                if ($iPurchaseId) {
                    if ($iDefaultCost > 0) {
                        define('PHPFOX_MUST_PAY_FIRST', $iPurchaseId);

                        Phpfox::getService('user.field.process')->update($iId, 'subscribe_id', $iPurchaseId);

                        return array(Phpfox::getLib('url')->makeUrl('subscribe.register', array('id' => $iPurchaseId)));
                    } else {
                        Phpfox::getService('subscribe.purchase.process')->update($iPurchaseId, $aPackage['package_id'], 'completed', $iId, $aPackage['user_group_id'], $aPackage['fail_user_group']);
                    }
                } else {
                    return false;
                }
            }
        }
        $this->database()->update(Phpfox::getT('user'), array('user_name' => 'profile-' . $iId), 'user_id = ' . $iId);
        return $iId;
    }

    public function addAgent($iUserId, $aData) {
        $aInsert = array(
            'user_id' => $iUserId,
            'identity' => $aData['identity'],
            'email' => $aData['email'],
            'service_id' => $aData['service_id'],
            'data' => serialize($aData),
            'created_time' => PHPFOX_TIME,
        );
        Phpfox::getLib('database')->insert(Phpfox::getT('sociallogin_agents'), $aInsert);
    }

    public function getAgentByIdentityAndService($iDentity, $iService) {
        $aRow = $this->database()->select('*')
                ->from(Phpfox::getT('sociallogin_agents'))
                ->where('identity="' . $iDentity . '" and service_id=' . $iService)
                ->execute('getRow');
        return $aRow;
    }

    public function getInfoUserPhpfox($email) {
        $aRow = $this->database()->select('*')
                ->from(Phpfox::getT('user'))
                ->where('email="' . $email . '"')
                ->execute('getRow');
        return $aRow;
    }

    public function checkemail($sEmail) {
        
        $aParam[] = 'email';
        if(Phpfox::getLib("validator")->check($sEmail,$aParam))
        {
            Phpfox_Error::set(Phpfox::getPhrase('user.provide_a_valid_email'));
            return 0;
        }
        $iCnt = $this->database()->select('COUNT(*)')
                ->from(Phpfox::getT('user'))
                ->where("email = '" . $this->database()->escape($sEmail) . "'")
                ->execute('getField');
        $is_not_error = 1;
        if ($iCnt) {
            $is_not_error = 0;
            Phpfox_Error::set(Phpfox::getPhrase('user.email_is_in_use_and_user_can_login', array('email' => trim(strip_tags($sEmail)), 'link' => Phpfox::getLib('url')->makeUrl('user.login', array('email' => base64_encode($sEmail))))));
        }

        if (!Phpfox::getService('ban')->check('email', $sEmail)) {
            $is_not_error = 0;
            Phpfox_Error::set(Phpfox::getPhrase('user.this_email_is_not_allowed_to_be_used'));
        }

        return $is_not_error;
    }

}

?>
